<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\project;

use app\enum\CommonEnum;
use app\enum\KsBidEnum;
use app\enum\KsCodeEnum;
use app\model\KsProjectBidTaskContentModel;
use app\model\KsProjectBidTaskLogModel;
use app\model\KsProjectBidTaskModel;
use app\service\client\AccountService;
use app\service\kuaishou\AdvertiserService;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class KsBidService extends ProjectService
{
    /**
     * 获取修改任务.
     * @param int $id 主键id
     * @return array|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getBidTask(int $id = 0)
    {
        // 返回数据
        return (new KsProjectBidTaskModel())->where('id', $id)->find();
    }

    /**
     * 获取修改任务数据.
     * @param KsProjectBidTaskModel $model 模型
     * @return array|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getBidTaskContent(KsProjectBidTaskModel $model)
    {
        $where = [];
        if ($model->getKey()) {
            $where[] = [
                'project_bid_id', '=', $model->getKey(),
            ];
        }
        // 返回数据
        return (new KsProjectBidTaskContentModel())->where($where)->select();
    }

    /**
     * 获取接口智能托管.
     * @param KsProjectBidTaskModel $model 任务模型
     * @return array|bool
     */
    public static function pullProject(KsProjectBidTaskModel $model, int $page = 1)
    {

        $advertiserId = $model->getAttr('advertiser_id');
        $token = AccountService::getToken(CommonEnum::KS_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'page' => $page,
            'page_size' => KsBidEnum::TASK_PAGE_SIZE,
        ];
        $result = AdvertiserService::getHostingProject($headers, $params);
        if (! $result) {
            return self::setError(self::getError(0));
        }
        return $result['data']['details'];
    }

    /**
     * 获取接口智能托管详情.
     * @param KsProjectBidTaskModel $model 任务模型
     * @return array|bool
     */
    public static function pullProjectDetail(KsProjectBidTaskModel $model, string $projectId = '')
    {
        $advertiserId = $model->getAttr('advertiser_id');
        $token = AccountService::getToken(CommonEnum::KS_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'project_id' => $projectId,
        ];
        $result = AdvertiserService::getHostingProjectDetail($headers, $params);
        if (! $result) {
            return self::setError(self::getError(0));
        }
        return $result['data'];
    }

    /**
     * 判断是否1和2type.
     * @param array $contentData 详情数据
     */
    public static function isDetailType(array $contentData = []): bool
    {
        foreach ($contentData as $content) {
            if (in_array($content['type'], [KsBidEnum::TASK_TYPE_ONE, KsBidEnum::TASK_TYPE_TWO, KsBidEnum::TASK_TYPE_FUR])) {
                return true;
            }
        }
        return false;
    }

    /**
     * 处理接口数据参数.
     * @param array $params 接口数据
     */
    public static function getApiParams(array $params = []): array
    {
        unset($params['campaign_id'], $params['put_status'], $params['create_time'], $params['update_time']);
        return $params;
    }

    /**
     * 判读是否该类型.
     * @param array $params 接口数据
     * @param int $type 类型
     */
    public static function isType(array $params = [], int $type = 0): bool
    {
        if ($type == KsBidEnum::TASK_TYPE_ONE && isset($params['enhance_conversion_type']) && $params['enhance_conversion_type'] == KsBidEnum::ENHANCE_TYPE_CONVERSION) {
            return false;
        }
        $compareFiled = KsBidEnum::TASK_TYPE_FIELD[$type];
        foreach ($compareFiled as $field => $value) {
            if (! isset($params[$field]) || $params[$field] != $value) {
                return false;
            }
        }
        return true;
    }

    /**
     * 修改智能托管.
     * @param KsProjectBidTaskModel $model 任务模型
     * @param array $params 参数
     * @return array|bool
     * @deprecated
     */
    public static function editProject(KsProjectBidTaskModel $model, array $params = [])
    {
        $params = self::getApiParams($params);
        $advertiserId = $model->getAttr('advertiser_id');
        $params['advertiser_id'] = $advertiserId;
        $token = AccountService::getToken(CommonEnum::KS_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $result = AdvertiserService::updateProject($headers, $params);
        if (! $result) {
            return $result;
        }
        if ($result['code'] != KsCodeEnum::SUCCESS) {
            return self::setError(json_encode($result, JSON_UNESCAPED_UNICODE));
        }
        return $result;
    }

    /**
     * 添加修改记录.
     * @param array $params 参数
     */
    public static function addBidLog(KsProjectBidTaskContentModel $contentModel, array $params = []): bool
    {
        if (! $contentModel->getKey()) {
            return self::setError('content数据不存在');
        }
        try {
            if ($params['project_id']) {
                $model = (new KsProjectBidTaskLogModel())->where([
                    ['project_id', '=', $params['project_id']],
                    ['project_content_id', '=', $contentModel->getKey()],
                ])->find();
                if (! $model instanceof KsProjectBidTaskLogModel || ! $model->getKey()) {
                    $model = new KsProjectBidTaskLogModel();
                }
            } else {
                $model = new KsProjectBidTaskLogModel();
            }
            $params['advertiser_id'] = $contentModel->getAttr('advertiser_id');
            $params['project_bid_id'] = $contentModel->getAttr('project_bid_id');
            $params['project_content_id'] = $contentModel->getKey();
            $model->setAttrs($params);
            return $model->save();
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 更新任务状态.
     * @param KsProjectBidTaskModel $model 模型
     * @param int $status 状态
     * @param int $num 数量
     */
    public static function updateTaskStatus(KsProjectBidTaskModel $model, int $status = 0, int $num = 0): bool
    {
        if (! $model->getKey()) {
            return self::setError('数据不存在');
        }
        try {
            $model->setAttr('status', $status);
            $model->setAttr('num', $num);
            return $model->save();
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }
}
